const path = require('path');
const glob = require('glob');
const { paths } = require('../../utils');

/*
  将
  {
    'common/common': 'common/index.js',
    'pages/*': 'pages/*\/index.js'
  }
  转换为
  {
    'common/common': '/Users/maben/work/test/fet-cli/fe-msk-pc/v5/src/common/index.js',
    'pages/about': '/Users/maben/work/test/fet-cli/fe-msk-pc/v5/src/pages/about/index.js',
    'pages/home': '/Users/maben/work/test/fet-cli/fe-msk-pc/v5/src/pages/home/index.js',
  }
*/

module.exports = function entrys(obj) {
  let result = Object.keys(obj).reduce((files, item) => {
    if (item.includes('*')) {
      if (!/^\//.test(obj[item])) {
        files = {
          ...files,
          ...spread(
            item, glob.sync(
              path.join(paths.contextPath, obj[item])
            )
          )
        };
      } else {
        files = {
          ...files,
          ...spread(
            item, glob.sync(obj[item])
          )
        };
      }
    } else {
      if (!/^\//.test(obj[item])) {
        files[item] = path.join(paths.contextPath, obj[item]);
      } else {
        files[item] = obj[item];
      }
    }
    return files;
  }, {});
  return result;
}

function spread(key, val){
  let arr = Array.isArray(val) ? val : [val];
  return arr.reduce((a, b) => {
    let folder = b.replace(new RegExp(`^.*${key.replace(/\*/, '')}([^/]+).*$`), '$1');
    return a[key.replace('*', folder)] = b, a;
  }, {});
}